/**
 * 导入公共逻辑
 */
const {
  BASE_API
} = process.env;

// import { enter2Br } from '@/utils/string';
import axios from 'axios';
import store from '@/store';
import { getToken } from '@/utils/auth';
import { mapState } from 'vuex';

export default {
  data() {
    return {
      uploadId: '',
      loading: false,
      cancelAxios: null,
      uploadPercent: 0
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    })
  },
  methods: {
    importList(service, url, formData, source) {
      this.loading = true;
      if (this.limitNum) {
        this.$message.warning('文件名称超过100个字，请修改后再试');
        this.loading = false;
        return true;
      }
      service.post(url, formData, {
        cancelToken: source.token || null
      }).then(({ data: { code, message, status, data }}) => {
        this.fileNameCopy = this.fileName;
        if (Number(code) === 200 && status) {
          this.loading = false;
          this.getList();
          this.$emit('handleSuccess');
        } else if (Number(code) === 401) {
          this.loading = false;
          this.$confirm(
            '当前登录已过期，请重新登录',
            '',
            {
              confirmButtonText: '重新登录',
              type: 'warning',
              customClass: 'del-message',
              iconClass: 'del-icon',
              showCancelButton: false,
              center: true
            }
          ).then(() => {
            this.loading = false;
            store.dispatch('FedLogOut').then(() => {
              location.reload(); // 为了重新实例化vue-router对象 避免bug
            });
          }).catch(() => {
            this.loading = false;
            return;
          });
        } else if (+code === 403 || +code === 500) {
          this.loading = false;
          if (this.customError) {
            this.$emit('handleError', message);
          } else {
            this.$message.error(message);
          }
        } else {
          this.loading = false;
          this.fileList = [];
        }
      }).catch((err) => {
        console.log(err);
        this.loading = false;
        this.fileList = [];
        this.getList();
      });
    },
    serviceToken(service) {
      service.interceptors.request.use(
        config => {
          const token = store.getters.token || getToken();
          if (token) {
            config.headers.common['token'] = token;
          }
          return config;
        },
        error => {
          console.log(error);
          Promise.reject(error);
        }
      );
    },
    beforeUpload(file) {
      const fileName = file.name;
      const fileNameTemp = file.name.replace(/\.xl(s|s[xmb]|t[xm]|am)$/, '');
      fileNameTemp.length > 100 ? this.limitNum = true : this.limitNum = false; // 判断文件名的长度
      this.fileName = fileName;
      if (this.uploadVerify && this.accept) {
        const fileSplitArr = this.fileName.split('.');
        const fileSuffix = fileSplitArr[fileSplitArr.length - 1];
        const result = this.accept.replace(/\s+/g, '').split(',').includes('.' + fileSuffix);
        if (!result) {
          this.$message.warning(`只能上传${this.accept}的文件`);
          return false;
        }
      }
    },
    uploadFileMethod(param) {
      const fileObject = param.file;
      const formData = new FormData();
      formData.append('fileData', fileObject);
      formData.append('fileName', this.fileName);
      if (this.isImportEdit) { // 是否为导入编辑
        formData.append('isImportEdit', this.isImportEdit);
        formData.append('uploadId', `${this.userInfo.id}${new Date().valueOf()}`);
      }
      // 额外的参数对象
      if (!_.isEmpty(this.extendParams) && Object.prototype.toString.call(this.extendParams) === '[object Object]') {
        Object.keys(this.extendParams).forEach(key => {
          formData.append(key, this.extendParams[key]);
        });
      }
      var source = axios.CancelToken.source();
      const service = axios.create({
        baseURL: BASE_API, // api 的 base_url
        timeout: 3600000, // 请求超时时间
        // timeout: 60000,
        headers: {
          'Content-Type': 'multipart/form-data;'
        },
        onUploadProgress: function(progressEvent) { // 获取进度条
          if (progressEvent.lengthComputable) {
            const lastPercent = this.uploadPercent;
            const total = progressEvent.total;
            const loaded = progressEvent.loaded;

            const uploadPercent = parseInt(loaded / total * 100);
            this.uploadPercent = lastPercent >= uploadPercent ? lastPercent : uploadPercent;
          }
        }
      });
      this.cancelAxios = source;
      this.serviceToken(service);
      this.importList(service, this.importApi, formData, source);
    },
    cancelHttp(msg = '请求已取消') {
      if (this.cancelAxios) {
        console.log('取消导入');
        this.cancelAxios.cancel(msg);
      }
    }
  }
};
